import sys
import os
from snakemake.utils import min_version

### set minimum snakemake version ###
#min_version('5.8.1')


Seqfile = config['SEQFILE']
Dbdir = config['DBDIR']
Provirus = config['PROVIRUS']

Groups = config['GROUPS']
Hmmsearch_threads = config['HMMSEARCH_THREADS']
General_threads = config['GENERAL_THREADS']
Hmmsearch_score_min = config['HMMSEARCH_SCORE_MIN']
Proba_cutoff = config['PROBA_CUTOFF']
Min_length = config['MIN_LENGTH']

Hallmark_required = config['HALLMARK_REQUIRED']
Hallmark_required_on_short = config['HALLMARK_REQUIRED_ON_SHORT']
Viral_gene_required = config['VIRAL_GENE_REQUIRED']

Contig_bp_per_split = config['CONTIG_BP_PER_SPLIT']
Faa_bp_per_split = config['FAA_BP_PER_SPLIT']
Gff_seqnum_per_split = config['GFF_SEQNUM_PER_SPLIT']
Max_orf_per_seq = config['MAX_ORF_PER_SEQ']

Tmpdir=config['TMPDIR']
Local_scratch=config['LOCAL_SCRATCH']
Prep_for_dramv = config['PREP_FOR_DRAMV']
Label = config['LABEL']
Keep_original_seq = config['KEEP_ORIGINAL_SEQ']
Seqname_suffix_off = config['SEQNAME_SUFFIX_OFF']

Label = f'{Label}-' if Label != '' else ''
Srcdir = srcdir('.')
Scriptdir='{}/scripts'.format(Srcdir)
Wkdir=os.path.abspath(os.getcwd())
Groups_str=' '.join(Groups)
Seqfile = os.path.abspath(Seqfile)
Conda_yaml_dir = '../envs' # relative to rules/*.smk files

pkg_dir = os.path.dirname(Srcdir)          
sys.path.append(os.path.abspath(pkg_dir))  # add virsorter 
sys.path.append(os.path.abspath(Scriptdir))   # add Scriptdir

wildcard_constraints:
    group='[A-Za-z]+',
    domain='[A-Za-z]+',
    shape='circular|linear',

include: 'rules/preprocess.smk'
include: 'rules/extract-feature.smk'
include: 'rules/classify.smk'

rule all:
    input:
        'Done-preprocess',
        'Done-extract-feature',
        'Done-classify',

rule preprocess:
    input:
        '{Tmpdir}/all.pdg.faa'.format(Tmpdir=Tmpdir),
        '{Tmpdir}/all.pdg.gff'.format(Tmpdir=Tmpdir),
    output:
        temp(touch('Done-preprocess'))
    shell:
        """
        echo "Step 1 - preprocess finished." | python {Scriptdir}/echo.py
        """


rule extract_feature:
    input:
        expand('{Tmpdir}/{{group}}/all.pdg.ftr'.format(Tmpdir=Tmpdir),
                group=Groups),
        'Done-preprocess',
    output:
        temp(touch('Done-extract-feature'))
    shell:
        """
        echo "Step 2 - extract-feature finished." | python {Scriptdir}/echo.py
        """

rule classify:
    input:
        f'{Label}final-viral-score.tsv',
        f'{Label}final-viral-combined.fa',
        'Done-extract-feature'
    output:
        temp(touch('Done-classify'))
    shell:
        """
        echo "Step 3 - classify finished." | python {Scriptdir}/echo.py
        """

container: "docker://continuumio/miniconda3:4.4.10"    

#onsuccess:
#    print('virsorter run finished')
onerror:
    if os.path.isfile('EARLY-EXIT'):
        sys.stderr.write('\n\n')
        sys.stderr.write(
                '*** This is NOT an bug; the virsorter run exited early due to specific condition of this sample; check the messages (INFO) above for more specific reasons; generally you can discard this sample\n\n'
        )
    else:
        sys.stderr.write('\n\n')
        sys.stderr.write(
                '*** An error occurred. Detailed errors may not be printed '
                'for certain rules. Refer to the log file of the failed '
                'command for troubleshooting\n'
        )
        sys.stderr.write(
                'Issues can be raised at: '
                'https://github.com/jiarong/VirSorter2/issues\n'
                'Or send an email to virsorter2 near gmail.com if '
                'you do not use GitHub\n\n'
        )

